/**
 * WebSocket服务 - 实时通信管理
 */

import { io } from 'socket.io-client'

/**
 * WebSocket服务类
 */
export class WebSocketService {
  constructor() {
    this.socket = null
    this.connected = false
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectInterval = 5000 // 5秒
    this.eventHandlers = new Map()
  }

  /**
   * 连接WebSocket
   */
  connect(url = null) {
    try {
      const socketUrl = url || window.location.origin
      
      this.socket = io(socketUrl, {
        transports: ['websocket', 'polling'],
        timeout: 20000,
        reconnection: true,
        reconnectionDelay: this.reconnectInterval,
        reconnectionAttempts: this.maxReconnectAttempts
      })

      // 连接事件处理
      this.socket.on('connect', () => {
        console.log('WebSocket连接已建立')
        this.connected = true
        this.reconnectAttempts = 0
        this._emit('connected')
      })

      this.socket.on('disconnect', (reason) => {
        console.log('WebSocket连接已断开:', reason)
        this.connected = false
        this._emit('disconnected', reason)
      })

      this.socket.on('connect_error', (error) => {
        console.error('WebSocket连接错误:', error)
        this.reconnectAttempts++
        this._emit('connection_error', error)
      })

      // 镜像更新相关事件
      this.socket.on('image_update_progress', (data) => {
        console.log('收到镜像更新进度:', data)
        this._emit('image_update_progress', data)
      })

      this.socket.on('image_update_complete', (data) => {
        console.log('镜像更新完成:', data)
        this._emit('image_update_complete', data)
      })

      this.socket.on('image_update_error', (data) => {
        console.error('镜像更新错误:', data)
        this._emit('image_update_error', data)
      })

      // 日志相关事件
      this.socket.on('execution_log', (data) => {
        console.log('收到执行日志:', data)
        this._emit('execution_log', data)
      })

      this.socket.on('system_status', (data) => {
        console.log('收到系统状态更新:', data)
        this._emit('system_status', data)
      })

      return this.socket
      
    } catch (error) {
      console.error('WebSocket连接失败:', error)
      this._emit('connection_error', error)
      throw error
    }
  }

  /**
   * 断开WebSocket连接
   */
  disconnect() {
    if (this.socket) {
      this.socket.disconnect()
      this.socket = null
      this.connected = false
      console.log('WebSocket连接已主动断开')
    }
  }

  /**
   * 发送消息
   */
  emit(eventName, data) {
    if (this.socket && this.connected) {
      this.socket.emit(eventName, data)
      console.log(`发送WebSocket消息: ${eventName}`, data)
    } else {
      console.warn('WebSocket未连接，无法发送消息')
    }
  }

  /**
   * 监听事件
   */
  on(eventName, handler) {
    if (!this.eventHandlers.has(eventName)) {
      this.eventHandlers.set(eventName, new Set())
    }
    this.eventHandlers.get(eventName).add(handler)
  }

  /**
   * 移除事件监听器
   */
  off(eventName, handler) {
    if (this.eventHandlers.has(eventName)) {
      this.eventHandlers.get(eventName).delete(handler)
    }
  }

  /**
   * 触发事件处理器
   */
  _emit(eventName, data = null) {
    if (this.eventHandlers.has(eventName)) {
      this.eventHandlers.get(eventName).forEach(handler => {
        try {
          handler(data)
        } catch (error) {
          console.error(`事件处理器执行失败 [${eventName}]:`, error)
        }
      })
    }
  }

  /**
   * 获取连接状态
   */
  isConnected() {
    return this.connected && this.socket && this.socket.connected
  }

  /**
   * 手动重连
   */
  reconnect() {
    if (this.socket && !this.connected) {
      this.socket.connect()
    }
  }

  /**
   * 设置重连参数
   */
  setReconnectConfig(maxAttempts, interval) {
    this.maxReconnectAttempts = maxAttempts
    this.reconnectInterval = interval
  }

  /**
   * 订阅镜像更新事件
   */
  subscribeToImageUpdate(callbacks) {
    if (callbacks.onProgress) {
      this.on('image_update_progress', callbacks.onProgress)
    }
    
    if (callbacks.onComplete) {
      this.on('image_update_complete', callbacks.onComplete)
    }
    
    if (callbacks.onError) {
      this.on('image_update_error', callbacks.onError)
    }
    
    if (callbacks.onLog) {
      this.on('execution_log', callbacks.onLog)
    }
    
    if (callbacks.onSystemStatus) {
      this.on('system_status', callbacks.onSystemStatus)
    }
  }

  /**
   * 取消订阅镜像更新事件
   */
  unsubscribeFromImageUpdate(callbacks) {
    if (callbacks.onProgress) {
      this.off('image_update_progress', callbacks.onProgress)
    }
    
    if (callbacks.onComplete) {
      this.off('image_update_complete', callbacks.onComplete)
    }
    
    if (callbacks.onError) {
      this.off('image_update_error', callbacks.onError)
    }
    
    if (callbacks.onLog) {
      this.off('execution_log', callbacks.onLog)
    }
    
    if (callbacks.onSystemStatus) {
      this.off('system_status', callbacks.onSystemStatus)
    }
  }
}

// 创建单例实例
export const webSocketService = new WebSocketService()

// 自动连接（可以根据需要禁用）
let autoConnectEnabled = true

export const setAutoConnectEnabled = (enabled) => {
  autoConnectEnabled = enabled
}

// 在适当的时候自动连接
if (typeof window !== 'undefined' && autoConnectEnabled) {
  // 延迟连接，确保页面加载完成
  setTimeout(() => {
    try {
      webSocketService.connect()
    } catch (error) {
      console.warn('自动WebSocket连接失败:', error)
    }
  }, 1000)
}

export default webSocketService